package me.shibor.study.servlet;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;


/**
 * ServletContext：
 *  void init(ServletConfig config) 默认情况下：第一次访问下创建Servlet（可修改），然后 调用init()
 *  void service(ServletRequest req, ServletResponse res)
 *  void destroy() 
 *
 */
public class ServletDemo2 implements Servlet{


	@Override
	public void destroy() {
		System.out.println("serlvetDemo2 销毁");
	}

	@Override
	public ServletConfig getServletConfig() {
		
		return null;
	}

	@Override
	public String getServletInfo() {
		
		return null;
	}


	@Override
	public void init(ServletConfig config) throws ServletException {
		
		System.out.println("serlvetDemo2组件被创建！");
		ServletContext context = config.getServletContext();
//		Enumeration<String> attributeNames = context.getAttributeNames();
		Enumeration<String> attributeNames = context.getInitParameterNames();
		while(attributeNames.hasMoreElements()) {
			String att = attributeNames.nextElement();
			String value = context.getInitParameter(att);
			System.out.println(att + ": " + value);
			
		}
		
		
		//项目目录
		String ContextPath = context.getContextPath();
		System.out.println("ContextPath: " + ContextPath);
		
		String realPath = context.getRealPath("/");
		System.out.println("RealPath: " + realPath);
		
	}


	@Override
	public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
		
		System.out.println("响应请求");
		
		//ServletContext servletContext = request.getServletContext();
		ServletContext servletContext = request.getServletContext();
		Integer count = (Integer)servletContext.getAttribute("count");
		if(count==null){
			count = 1;
		} else {
			System.out.println("count: " + ++count);
		}
		servletContext.setAttribute("count", count);
		
		String notice = "<h2>点击了 " + count + " 次</ha2>";
		
		
		response.getOutputStream().write("<font color='pink'> serlvetDemo2</font>".getBytes());
		response.getOutputStream().write(notice.getBytes());
		response.getOutputStream().write("!!!".getBytes());
		
	}

}
